'use strict';

const bcrypt = require('bcryptjs');
const Service = require('egg').Service;

class UserService extends Service {
  // 根据用户名查找用户
  async findByUsername(username) {
    const user = await this.app.mysql.get('users', { username });
    return user;
  }

  // 根据邮箱查找用户
  async findByEmail(email) {
    const user = await this.app.mysql.get('users', { email });
    return user;
  }

  // 创建用户
  async create(userData) {
    const { username, password, email, phone } = userData;
    
    // 检查用户名是否已存在
    const existingUser = await this.findByUsername(username);
    if (existingUser) {
      throw new Error('用户名已存在');
    }

    // 检查邮箱是否已存在
    const existingEmail = await this.findByEmail(email);
    if (existingEmail) {
      throw new Error('邮箱已存在');
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入用户数据
    const result = await this.app.mysql.insert('users', {
      username,
      password: hashedPassword,
      email,
      phone,
      role: 'user',
      status: 'active',
      created_at: new Date(),
      updated_at: new Date(),
    });

    return result;
  }

  // 验证密码
  async validatePassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
  }

  // 更新用户信息
  async update(id, userData) {
    userData.updated_at = new Date();
    const result = await this.app.mysql.update('users', userData, {
      where: { id },
    });
    return result;
  }

  // 根据ID查找用户
  async findById(id) {
    const user = await this.app.mysql.get('users', { id });
    return user;
  }

  // 获取所有用户
  async findAll() {
    const users = await this.app.mysql.select('users');
    return users;
  }

  // 更新用户个人信息
  async updateProfile(id, data) {
    const { username, email, phone, avatar, real_name, gender, birthday, address, bio } = data;
    
    const updateData = {};
    if (username !== undefined) updateData.username = username;
    if (email !== undefined) updateData.email = email;
    if (phone !== undefined) updateData.phone = phone;
    if (avatar !== undefined) updateData.avatar = avatar;
    if (real_name !== undefined) updateData.real_name = real_name;
    if (gender !== undefined) updateData.gender = gender;
    if (birthday !== undefined) updateData.birthday = birthday;
    if (address !== undefined) updateData.address = address;
    if (bio !== undefined) updateData.bio = bio;
    
    updateData.updated_at = new Date();

    const result = await this.app.mysql.update('users', updateData, {
      where: { id },
    });

    return result;
  }

  // 修改密码
  async changePassword(id, oldPassword, newPassword) {
    const user = await this.findById(id);
    if (!user) {
      throw new Error('用户不存在');
    }

    // 验证旧密码
    const isOldPasswordValid = await this.validatePassword(oldPassword, user.password);
    if (!isOldPasswordValid) {
      throw new Error('原密码错误');
    }

    // 加密新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);

    const result = await this.app.mysql.update('users', {
      password: hashedNewPassword,
      updated_at: new Date(),
    }, {
      where: { id },
    });

    return result;
  }

  // 获取用户统计信息
  async getUserStats(id) {
    // 获取用户发布的房源数量
    const propertiesCount = await this.app.mysql.count('houses', {
      user_id: id
    });

    // 获取用户的预约数量
    const appointmentsCount = await this.app.mysql.count('appointments', {
      user_id: id
    });

    // 获取用户的评价数量
    const reviewsCount = await this.app.mysql.count('property_reviews', {
      user_id: id
    });

    return {
      properties_count: propertiesCount,
      appointments_count: appointmentsCount,
      reviews_count: reviewsCount
    };
  }
}

module.exports = UserService;